import { useLoginUserStore } from 'store/modules/LoginUserStore'
import { useRequest } from 'vue-request'
import { useRoute, useRouter } from 'vue-router'
import { ElForm } from 'element-plus'
import { reactive, ref } from 'vue'
import { LoginParamType } from '@/services/LoginService'
import { HOME_ROUTE_NAME } from 'utils/SystemConstants'

export function useLogin() {
  const loginStore = useLoginUserStore()
  const { loading, run: doLogin } = useRequest(loginStore.doLogin, {
    manual: true,
  })

  const $router = useRouter()
  const $route = useRoute()

  type FormInstance = InstanceType<typeof ElForm>
  const elFormRef = ref<FormInstance>()
  const loginFormRule = {
    username: [
      {
        required: true,
        message: '请输入账号',
        trigger: 'blur',
      },
    ],
    pwd: [
      {
        required: true,
        message: '请输入密码',
        trigger: 'blur',
      },
    ],
  }
  const loginFormData = reactive<LoginParamType>({
    username: 'test',
    pwd: 'test',
  })
  function onSubmit() {
    if (!elFormRef.value) return
    elFormRef.value.validate(async valid => {
      if (valid) {
        await doLogin(loginFormData)
        if ($route.query.callback) {
          await $router.push({ path: $route.query.callback as string })
        } else {
          await $router.push({ name: HOME_ROUTE_NAME })
        }
      } else {
        console.log('error submit!')
        return false
      }
    })
  }
  return { loading, loginFormData, onSubmit, elFormRef, loginFormRule }
}
